package utils;


import com.jcraft.jsch.JSchException;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ApisProduction {

    public static void main(String[] args) throws IOException {
        new ApisProduction().productionFromClipboard();

    }

    private void productions(String url, String logsurl) throws IOException, JSchException {
        List<String> logs = RemoteOperation.newInstance().executeCommand(logsurl + " && grep '" + url + "' access_80.log |tail -n 1");
        System.out.println(logs);
        File file = new File("template.txt");
        File filejson = new File("templateJson.json");
        Utils.newInstanceUtils().checkFile(file);
        Utils.newInstanceUtils().checkFile(filejson);

        System.out.println(file.getAbsolutePath());
        if (logs.isEmpty()) {
            System.out.println("没有查询到日志");
            return;
        }
        String data = URLDecoder.decode(logs.get(0).replace("^", "@"), StandardCharsets.UTF_8);
        String regex = "@(.+)@";
        String json = "";
        Pattern pa = Pattern.compile(regex);
        Matcher ma = pa.matcher(data);
        while (ma.find()) {
            json = ma.group(1);
        }
        System.out.println(json);
        if (!"-".equals(json)) {
            json = json.replace("\\x22", "\"");
            if (json.startsWith("{") | json.startsWith("[")) {
                Utils.newInstanceUtils().fileOutPut(filejson, json);
            } else {
                String[] list = json.split("&");
                Utils.newInstanceUtils().fileOutPut(file, "Map<String, Object> map = new HashMap<>();");
                for (String str : list) {
                    String[] kv = str.split("=");
                    if (kv.length == 1)
                        Utils.newInstanceUtils().fileOutPut(file, "map.put(\"" + kv[0] + "\"," + "\"\"" + ");");
                    else
                        Utils.newInstanceUtils().fileOutPut(file, "map.put(\"" + kv[0] + "\"," + kv[1] + ");");
                }
            }
        }
        if (data.contains("GET")) {
            String regex1 = url + "\\?(.+) HTTP.+";
            String getData = "";
            Pattern pa1 = Pattern.compile(regex1);
            Matcher ma1 = pa1.matcher(data);

            while (ma1.find()) {
                getData = ma1.group(1);
            }
            if (!"".equals(getData)) {

                String dedata = URLDecoder.decode(getData, StandardCharsets.UTF_8);
                String[] list = dedata.split("&");
                Utils.newInstanceUtils().fileOutPut(file, "Map<String, Object> map = new HashMap<>();");
                for (String str : list) {
                    String[] kv = str.split("=");
                    Utils.newInstanceUtils().fileOutPut(file, "map.put(\"" + kv[0] + "\"," + kv[1] + ");");
                }
            }
        }
    }

    /**
     * 1、在测试服务器 Nginx 读取最新的请求参数
     * 2、根据接口路径在工程api目录下生成相应路径的请求类
     * 3、解析参数自动生成api请求代码及请求参数
     *
     * @param url
     * @param logsurl
     * @throws IOException

     */
    private void production(String url, String logsurl) throws IOException, JSchException {
        Utils utils = Utils.newInstanceUtils();
        List<String> logs = RemoteOperation.newInstance().executeCommand(logsurl + " && grep '" + url + "' access_80.log |tail -n 1");
        System.out.println(logs);
        if (logs.isEmpty()) {
            System.out.println("没有查询到日志");
            return;
        }
        String regex = "(.+)";
        String json = "";
        Pattern pa = Pattern.compile(regex);
        Matcher ma = pa.matcher(logs.get(0));
        while (ma.find()) {
            json = ma.group(1);
        }
        System.out.println(json);
        System.out.println(ma.groupCount());
        File file_data = new File(Config.http_srcUrl + url + ".json");
        file_data.mkdirs();
        utils.checkFile(file_data);
        utils.fileOutPut(file_data, json);
        //根据请求数据文件自动生成网络请求
        String[] arr = url.split("/");

        StringBuilder name = new StringBuilder();
        String url$ = null;
        for (String str : arr) {
            char[] cs = str.toCharArray();
            cs[0] -= 32;
            name.append(String.valueOf(cs));
        }
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length - 2) {
                break;
            }
            url$ = arr[i] + "/" + arr[i + 1] + "/";
        }
        File file_scr = new File(Config.http_srcUrl + url$ + name + ".java");
        file_scr.mkdirs();
        utils.checkFile(file_scr);
//        StringBuilder sb=new StringBuilder();
//        utils.fileRead(file_data).forEach(sb::append);

        utils.fileOutPut(file_scr, "package AutoApis_mis_request." + url$.replace("/", ".").substring(0, url$.length() - 1) + ";");
        utils.fileOutPut(file_scr, "import apis.ApisProperties;\n" +
                "import org.json.JSONObject;\n" +
                "import utils.Config;\n" +
                "import utils.Utils;\n" +
                "import java.io.File;\n" +
                "import java.util.HashMap;\n" +
                "import java.util.Iterator;\n" +
                "import java.util.Map;");
        utils.fileOutPut(file_scr, "public class " + name + " extends ApisProperties {");
        utils.fileOutPut(file_scr, "public String doHttp(Map<String,Object> otherMap) throws Exception{");
        utils.fileOutPut(file_scr, "String url=\"" + url + "\";");
        utils.fileOutPut(file_scr, "File file_data=new File(Config.http_srcUrl+url+\".json\");");
        utils.fileOutPut(file_scr, "StringBuilder sb=new StringBuilder();");
        utils.fileOutPut(file_scr, "Utils.newInstanceUtils().fileRead(file_data).forEach(sb::append);");

        utils.fileOutPut(file_scr, "JSONObject jsonObject1=new JSONObject(sb.toString().replace(\" \",\"\"));");
        utils.fileOutPut(file_scr, " Map<String, Object> map = new HashMap<>();");
        utils.fileOutPut(file_scr, "Iterator it = jsonObject1.keys();");
        utils.fileOutPut(file_scr, "while (it.hasNext()) {");
        utils.fileOutPut(file_scr, "String key = (String) it.next();map.put(key, jsonObject1.optString(key));}if (otherMap!=null){ otherMap.forEach(map::put); }");
        utils.fileOutPut(file_scr, "return http_mis().doPost(url, map);");
        utils.fileOutPut(file_scr, "}}");
    }

    /**
     * 先手动复制请求的参数到剪贴板中，然后自动读取剪贴板内容自动生成请求参数
     */
    public void productionFromClipboard() throws IOException {
        File file = new File("template.txt");
        Utils.newInstanceUtils().checkFile(file);

        String text = Utils.newInstanceUtils().getSysClipboardText();
        Utils.newInstanceUtils().fileOutPut(file, "Map<String, Object> map = new HashMap<>();");
        String[] lines = text.split(System.getProperty("line.separator"));
        for (String line : lines) {
            System.out.println(line);
//            System.out.println(line.split(" ")[1]);
            String[] k = line.split("\t");
            if (k.length == 1)
                Utils.newInstanceUtils().fileOutPut(file, "map.put(\"" + k[0] + "\"," + "\"\");");
            else
                Utils.newInstanceUtils().fileOutPut(file, "map.put(\"" + k[0] + "\",\"" + k[1]+"\");");
        }
    }

}
